package me
import grails.converters.JSON
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
import groovy.sql.Sql
import groovy.json.*
import groovy.json.JsonSlurper
import grails.plugins.rest.client.RestBuilder
import oracle.jdbc.pool.OracleDataSource;

class UserloginController {

	   def dataSource

    def index() { 

    	
    }

    def logout() {
        def results = [:]   
        session.userLogin = null
        render results as JSON
    }

  	def store() {
  		def sql = new Sql(dataSource)
   		def results = [:]	  
      def userLoginName =params.userLoginName
      def userLoginPassword = params.userLoginPassword
    	def rows

      if (userLoginName==null || userLoginName=="") {
        rows = sql.rows("select * from user_login")
        results.total = rows.size()
        results = [success:true,total:rows.size(),results:rows]
      } else {
        rows = sql.rows("select * from user_login where user_login_name=?",userLoginName)
        if (rows.size()!=0) {
            if (userLoginPassword.encodeAsMD5()==rows[0].password) {
              results = [success:true]
              session.userLogin = rows[0]
            } else {
              results = [success:false,message:"用户名或密码错误"] 
            }
        } else {
          results = [success:false,message:"用户名或密码错误"]
        }
      }
    	

      


      /*def rest = new RestBuilder()
      def resp = rest.get("http://120.55.58.28/rfidApi/carQueue")
      def json = resp.json
      println json*/

    	render results as JSON
  	}


  	def delete() {
  		def userLogin = UserLogin.findById(params.id)
  		println userLogin
  		userLogin.delete(flush: true) 
  		def results = [success:true]
    	render results as JSON
  	}

  
  	def save() {

  		def sql = new Sql(dataSource)
   		def results = [success:true,message:'success']
   		def userLoginId = params.userLoginId
      def userLoginName = params.userLoginName
      def userLoginPassword = params.userLoginPassword

      if(userLoginPassword!=null && userLoginPassword!="") {
        userLoginPassword = userLoginPassword.encodeAsMD5()
      }



   		if (userLoginId==null || userLoginId=="") {

          def rows = sql.rows("select * from user_login where user_login_name=?",userLoginName)
          if (rows.size()!=0) {
              results = [success:false,message:'用户名已存在']  
          } else {
              def userLogin = new UserLogin(userLoginName: userLoginName, password:userLoginPassword)
              userLogin.save(failOnError: true)
          }
          
   		} else {

   			  def userLogin = UserLogin.findById(userLoginId)
   			  userLogin.userLoginName = userLoginName    
   			  userLogin.password = userLoginPassword     
   			
     			try {
    	       userLogin.save(failOnError: true,flush: true) 
    			}
    			catch (e) { 
    			    println e
    			}
   		
      }
    	
    	render results as JSON
  	
    }

}
